package TwoPointers;

import java.util.Arrays;

public class _16_3SumClosest {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int tempSum = nums[left] + nums[right] + nums[i];
                if (tempSum == target) {
                    return tempSum;
                } else if (tempSum < target) {
                    if (Math.abs(target - tempSum) < Math.abs(res - target)) {
                        res = tempSum;
                    }
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    left++;
                } else {
                    if (Math.abs(target - tempSum) < Math.abs(target - res)) {
                        res = tempSum;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    right--;
                }

            }
        }
        return res;
    }
}
